#include <array>
#include <iostream>
#include <stdexcept>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

constexpr uint16_t port = 12345;
constexpr size_t BUFFERSIZE = BUFSIZ;
static_assert(BUFFERSIZE > 0);

class EchoServer
{
  public:
    explicit EchoServer(uint16_t port) : cli_{.sin6{}}, ser_{.sin6{}}
    {
        if (fd_ = ::socket(AF_INET, SOCK_DGRAM, 0); fd_ < 0)
        {
            throw std::runtime_error(strerror(errno));
        }
        ser_.sin.sin_family = AF_INET;
        ser_.sin.sin_port = htons(port);
        ser_.sin.sin_addr.s_addr = htonl(INADDR_ANY);
        if (Bind() < 0)
        {
            throw std::runtime_error(strerror(errno));
        }
    }

    void Echo()
    {
        while (true)
        {
            std::array<char, BUFFERSIZE> buf{};
            if (auto len = Recv(buf); len != 0)
            {
                Send(buf, buf.size());
            }
            else
            {
                throw std::runtime_error(strerror(errno));
            }
        }
    }

    ~EchoServer()
    {
        ::close(fd_);
    }

  private:
    int Bind()
    {
        return ::bind(fd_, &ser_.sa, sizeof(ser_.sin));
    }

    ssize_t Recv(std::array<char, BUFFERSIZE>& buf)
    {
        socklen_t cLen = sizeof(cli_.sin);
        return ::recvfrom(fd_, buf.data(), buf.size(), 0, &cli_.sa, &cLen);
    }

    ssize_t Send(std::array<char, BUFFERSIZE>& buf, ssize_t len)
    {
        if (len > buf.size())
        {
            throw std::runtime_error("len >= buf.size()");
        }
        return ::sendto(
            fd_, buf.data(), buf.size(), 0, &cli_.sa, sizeof(cli_.sin));
    }

    int fd_{};
    union addr
    {
        sockaddr_in6 sin6;
        sockaddr_in sin;
        sockaddr sa;
    };
    addr cli_;
    addr ser_;
};

using namespace std;
int main(int argc, char** argv)
{
    EchoServer server(port);
    try
    {
        server.Echo();
    }
    catch (std::exception& e)
    {
        std::cout << e.what() << std::endl;
    }
    return 0;
}